package cn.gok.gokhappymall.service.impl;

import cn.gok.gokhappymall.common.ServerResponse;
import cn.gok.gokhappymall.dao.CategoryMapper;
import cn.gok.gokhappymall.dao.ProductMapper;
import cn.gok.gokhappymall.entity.Category;
import cn.gok.gokhappymall.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: chenfan
 * @Description:
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    CategoryMapper categoryMapper;


    /**
     获取子节点
     比如 1001  0  数码3c
                     10001 1001 手机
                     10002 1001  平板电脑
     */
    @Override
    public ServerResponse<List<Category>> queryCategoriesByParentCategoryId(Integer parentCategoryId){

        Map<String, Object> param = new HashMap<>();

        Category category = categoryMapper.selectById(parentCategoryId);
        if (category == null){
            return ServerResponse.createByErrorMessage("未找到该品类");
        }

        param.put("parent_id",parentCategoryId);
        List<Category> categories = categoryMapper.selectByMap(param);
        return ServerResponse.createBySuccess(categories);

    }

    @Override
    public ServerResponse addCategorie(Integer parentCategoryId, String categoryName) {

        Category category = new Category();
        category.setParentId(parentCategoryId);
        category.setName(categoryName);

        int i = categoryMapper.insert(category);
        if (i > 0){
            return ServerResponse.createBySuccess("添加成功");
        }

        return ServerResponse.createByErrorMessage("添加失败");
    }


    @Override
    public ServerResponse<List<Integer>> queryCategoryAndChildrenId(Integer categoryId){

        ArrayList<Integer> categorieIds = new ArrayList<>();
        Set<Category> categories = new HashSet<>();

        //递归查询出所有的字节点
        findChildrenCategory(categories,categoryId);


        //封装到List<Integer>中
        for (Category category : categories) {
            categorieIds.add(category.getId());
        }

       return ServerResponse.createBySuccess(categorieIds);
    }


    /**
     * 递归找子节点的方法
     */
    private Set<Category> findChildrenCategory(Set<Category> categories,Integer categoryId){

        //根据id查出Category本身数据
        Category category = categoryMapper.selectById(categoryId);

        //查询出以后存入Set<Category>中
        if(category != null){
            categories.add(category);
        }

        //以categoryId作为父id 去查询其下是否还有子节点
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("parent_id",categoryId);
        List<Category> categoryList = categoryMapper.selectByMap(hashMap);

        for (Category categoryItem : categoryList) {

            //调用方法本身
            findChildrenCategory(categories,categoryItem.getId());
        }

        return categories;
    }





}
